package com.googlecode.linkmein.service;

import com.googlecode.linkmein.domain.*;
import com.googlecode.linkmein.repository.GDocRepository;
import com.googlecode.linkmein.repository.ObjectStorage;

public class FetchEmployeeService {
    public static FetchEmployeeService employeesCache;
    private Employees employees = new Employees();
    private Projects projects = new Projects();
    private GDocRepository gDocRepository;
    private PicasaService picasaService;
    private CompareRevisionService compareRevisionService;
    private ObjectStorage storage;
    private int counter;

    public FetchEmployeeService(GDocRepository gDocRepository,
                                PicasaService picasaService, CompareRevisionService compareRevisionService,
                                ObjectStorage storage) throws Exception {
        this.gDocRepository = gDocRepository;
        this.picasaService = picasaService;
        this.compareRevisionService = compareRevisionService;
        this.counter = 0;
        this.storage = storage;
    }

    public Employees getEmployees() {
        return employees;
    }

    public Projects getProjects() {
        return projects;
    }

    private Resources findResources() throws Exception {
        return new Resources(gDocRepository.entries("TW China Resource Schedule", "Resource Schedules"));
    }

    private Contacts findContacts() throws Exception {
        return new Contacts(gDocRepository.entries("TW China Contact List", "Contact Details"));
    }

    public Gossipies findGossipies() throws Exception {
        return Gossipies.load(gDocRepository.entries("TWCN个人信息及共享情报", "个人信息"));
    }

    private Albums findAlbums(Contacts contracts) {
        return picasaService.findAlbums(contracts);
    }

    private MapInfoes findMapInfoes() {
        return MapInfoes.load(storage);
    }

    public void refresh() throws Exception {
        Contacts contacts = findContacts();
        Resources resources = findResources();
        Gossipies gossipies = findGossipies();
        Albums albums = new Albums();
        if (counter > 0) {
            albums = findAlbums(contacts);
        }
        MapInfoes mapInfoes = findMapInfoes();

        Employees newEmployees = Employees.get(contacts, resources, gossipies, albums, mapInfoes);
        Projects newProjects = Projects.get(newEmployees);
        if (counter++ != 0) { // do not store revisions when the container initially start and this service fetch data first time
            compareRevisionService.compareAndStoreEmployeesRevision(employees, newEmployees);
            compareRevisionService.compareAndStoreProjectsRevision(projects, newProjects);
        }
        employees = newEmployees;
        projects = newProjects;
    }

}
